<?php
/***************************************************************
 *  Copyright notice
 *
 *  (c) 2014 TaoJIang <ribeter267@gmail.com>
 *  All rights reserved
 *
 *  This script is part of the TYPO3 project. The TYPO3 project is
 *  free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  The GNU General Public License can be found at
 *  http://www.gnu.org/copyleft/gpl.html.
 *
 *  This script is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  This copyright notice MUST APPEAR in all copies of the script!
 ***************************************************************/

// require_once(PATH_tslib . 'class.tslib_pibase.php');

/**
 * Plugin '志愿者管理' for the 'mfwc_volunteer' extension.
 *
 * @author	TaoJIang <ribeter267@gmail.com>
 * @package	TYPO3
 * @subpackage	tx_mfwcvolunteer
 */
class tx_mfwcvolunteer_pi1 extends tslib_pibase {
	public $prefixId      = 'tx_mfwcvolunteer_pi1';		// Same as class name
	public $scriptRelPath = 'pi1/class.tx_mfwcvolunteer_pi1.php';	// Path to this script relative to the extension dir.
	public $extKey        = 'mfwc_volunteer';	// The extension key.

	
	/**
	 * The main method of the Plugin.
	 *
	 * @param string $content The Plugin content
	 * @param array $conf The Plugin configuration
	 * @return string The content that is displayed on the website
	 */
	public function main($content, array $conf) {
	
		$this->init($conf);
		
		switch($this->flex['what_to_display']){
			
			case 'list':
				$content .= $this->listView();
				break;
				
			case 'detail':
				$content .= $this->detailView();
				break;
				
			case 'favorite':
				$content .= $this->favoriteView();
				break;
				
			case 'mlist':
				$content .= $this->managerListView();
				break;
			
			case 'mdetail':
				$content .= $this->managerDetailView();
				break;
		}
	
		return $this->pi_wrapInBaseClass($content);
	}
	
	
	/**
	 * 志愿者列表
	 */
	function listView(){
		
		
		$this->volunteerAddId(); //志愿者增加编号
		
		$this->doFavorite();
		
		$tpl = $this->cObj->getSubpart($this->template, '###LIST_VIEW###');
		$tpl_items = $this->cObj->getSubpart($tpl, '###ITEMS###'); 
		$item_fileds = $this->lib->getMarkerNames($tpl_items,'INFO');

		$where = 'disable=0 AND deleted=0 AND FIND_IN_SET('.$this->flex['volunteerGroup'].',usergroup)';
		$res = $this->db->exec_SELECTquery('uid,'.implode(',',$item_fileds),'fe_users',$where,'','tx_mfwcvolunteer_id DESC');
		while($row = $this->db->sql_fetch_assoc($res)){
			
			$temp_mk = $this->lib->getMarkerInfo($item_fileds,'fe_users','INFO',$row);
			$temp_mk['###BTN_VIEW###'] = $this->lib->linkButton('查看',$this->lib->selfT3Url(array('uid'=>$row['uid'],'back'=>$this->backurl),$this->flex['detailPid']),'','btn-mini',TRUE);
			
			//if($this->db->exec_SELECTcountRows('uid','tx_mfwcvolunteer_favorite','uid_local='.$row['uid'].' AND uid_foreign='.$this->userData['uid']) > 0){
			//	$temp_mk['###BTN_FAVORITE###'] = $this->lib->linkButton('取消收藏',$this->lib->selfT3Url(array('uid'=>$row['uid'],'cmd'=>'favorite','status'=>2,'back'=>$this->backurl),$GLOBALS['TSFE']->id),'icon-flag','btn-mini',FALSE,TRUE);
			//}else{
				$temp_mk['###BTN_FAVORITE###'] = $this->lib->linkButton('收藏',$this->lib->selfT3Url(array('uid'=>$row['uid'],'cmd'=>'favorite','status'=>1,'back'=>$this->backurl),$GLOBALS['TSFE']->id),'icon-flag','btn-mini',FALSE,TRUE);
			//}
			
			$content_items .= $this->cObj->substituteMarkerArray($tpl_items,$temp_mk);
		}
		
		$this->db->sql_free_result($res);
		$content = $this->cObj->substituteSubpart($tpl,'###ITEMS###',$content_items);
		
		
		$mk = array(
			'###HEADER###' => $this->cObj->data['header'],
		);

		$content = $this->cObj->substituteMarkerArray($content,$mk);
		return $content;
	}
	
	
	
	/**
	 * 志愿者详细信息
	 */
	function detailView(){
		
		
		
		$this->doFavorite();
		
		$tpl = $this->cObj->getSubpart($this->template, '###DETAIL_VIEW###');
		$fileds = $this->lib->getMarkerNames($tpl,'INFO');
		
		//debug($fileds,'$fileds');
		//debug($this->db->SELECTquery('uid,'.implode(',',$fileds),'fe_users', 
		//	'deleted=0 AND disable=0 AND FIND_IN_SET('.$this->flex['volunteerGroup'].',usergroup) AND uid='.$this->get['uid']),'sql');
		
		if($this->get['uid'] && $data = $this->db->exec_SELECTgetSingleRow('uid,'.implode(',',$fileds),'fe_users', 
			'deleted=0 AND disable=0 AND FIND_IN_SET('.$this->flex['volunteerGroup'].',usergroup) AND uid='.$this->get['uid'])){
		
			$mk = $this->lib->getMarkerInfo($fileds,'fe_users','INFO',$data);
			$mk['###HEADER###'] = $this->cObj->data['header'];
			$mk['###MSG###'] = $this->msg;
			$mk['###BTN_BACK###'] = $this->lib->closeButton();
			
			if($this->db->exec_SELECTcountRows('uid','tx_mfwcvolunteer_favorite','uid_local='.$this->get['uid'].' AND uid_foreign='.$this->userData['uid']) > 0){
				$mk['###BTN_FAVORITE###'] = $this->lib->linkButton('取消收藏',$this->lib->selfT3Url(array('uid'=>$this->get['uid'],'cmd'=>'favorite','reload'=>1,'status'=>2,'back'=>$this->backurl),$GLOBALS['TSFE']->id),'icon-flag','',TRUE,TRUE);
			}else{
				$mk['###BTN_FAVORITE###'] = $this->lib->linkButton('收藏',$this->lib->selfT3Url(array('uid'=>$this->get['uid'],'cmd'=>'favorite','reload'=>1,'status'=>1,'back'=>$this->backurl),$GLOBALS['TSFE']->id),'icon-flag','',TRUE,TRUE);
			}
			
			return $this->cObj->substituteMarkerArray($tpl,$mk);
		}
		
		return '你要找的信息不存在';
	}
	
	
	
	
	/**
	 * 志愿者收藏
	 */
	function favoriteView(){
		
		
		$this->doFavorite();
		
		$tpl = $this->cObj->getSubpart($this->template, '###LIST_VIEW###');
		$tpl_items = $this->cObj->getSubpart($tpl, '###ITEMS###'); 
		$item_fileds = $this->lib->getMarkerNames($tpl_items,'INFO');
		
		$select = 'fe_users.uid';
		foreach($item_fileds as $filed){
			$select .= ',fe_users.'.$filed;
		}
		
		$res = $this->db->exec_SELECT_mm_query($select,
			'fe_users','tx_mfwcvolunteer_favorite','fe_users',
			' AND uid_foreign='.$this->userData['uid'].' AND fe_users.disable=0 AND fe_users.deleted=0 AND FIND_IN_SET('.$this->flex['volunteerGroup'].',fe_users.usergroup)');
	
		while($row = $this->db->sql_fetch_assoc($res)){
			
			$temp_mk = $this->lib->getMarkerInfo($item_fileds,'fe_users','INFO',$row);
			$temp_mk['###BTN_VIEW###'] = $this->lib->linkButton('查看',$this->lib->selfT3Url(array('uid'=>$row['uid'],'back'=>$this->backurl),$this->flex['detailPid']),'','btn-mini',TRUE);
			$temp_mk['###BTN_FAVORITE###'] = $this->lib->linkButton('取消收藏',$this->lib->selfT3Url(array('uid'=>$row['uid'],'cmd'=>'favorite','reload'=>1,'status'=>2,'back'=>$this->backurl),$GLOBALS['TSFE']->id),'icon-flag','btn-mini',FALSE,TRUE);
			
			$content_items .= $this->cObj->substituteMarkerArray($tpl_items,$temp_mk);
		}
		
		$this->db->sql_free_result($res);
		$content = $this->cObj->substituteSubpart($tpl,'###ITEMS###',$content_items);
		
		
		$mk = array(
			'###HEADER###' => $this->cObj->data['header'],
		);
		
		$content = $this->cObj->substituteMarkerArray($content,$mk);
		return $content;
	}
	
	
	
	
	
	/**
	 * 收藏
	 */
	function doFavorite(){
		
		
		if($this->userData['uid'] && $this->get['uid'] && $this->get['cmd'] && 'favorite' == $this->get['cmd']){
			
			$url = '';
			if($this->get['reload'] && $this->get['reload'] == 1){
				$url = urldecode($this->backurl);
			}
		
			if($this->get['status'] && $this->get['status'] == 2){

				$this->db->exec_DELETEquery('tx_mfwcvolunteer_favorite','uid_local='.$this->get['uid'].' AND uid_foreign='.$this->userData['uid']);
				$this->lib->doLayout(array('message' => '取消收藏成功', 'url' => $url));
				
			}else{
			
				if($this->db->exec_SELECTcountRows('uid','tx_mfwcvolunteer_favorite','uid_local='.$this->get['uid'].' AND uid_foreign='.$this->userData['uid']) < 1)
				{
					$ins = array(
						'tstamp' => strtotime('now'),
						'uid_local' => $this->get['uid'],
						'uid_foreign' => $this->userData['uid'],
					);
					
					$this->db->exec_INSERTquery('tx_mfwcvolunteer_favorite', $ins);
				}
				
				$this->lib->doLayout(array('message' => '收藏成功','url' => $url));
			}
		}
	}
	

	
	
	
	
	/**
	 * 部门列表
	 */
	function managerListView(){
		
		$this->doDeleteManager(); //部分删除
		
		$tpl = $this->cObj->getSubpart($this->template, '###MLIST_VIEW###');
		$tpl_items = $this->cObj->getSubpart($tpl, '###ITEMS###'); 
		$item_fileds = $this->lib->getMarkerNames($tpl_items,'INFO');

		$res = $this->db->exec_SELECTquery('uid,'.implode(',',$item_fileds),'tx_mfwcvolunteer_departments','deleted=0 AND hidden=0','','uid asc');
		while($row = $this->db->sql_fetch_assoc($res)){
			
			$temp_mk = $this->lib->getMarkerInfo($item_fileds,'tx_mfwcvolunteer_departments','INFO',$row);
			$temp_mk['###BTN_VIEW###'] = $this->lib->linkButton('查看',$this->lib->selfT3Url(array('uid'=>$row['uid'],'back'=>$this->backurl),$this->flex['detailPid']),'','btn-mini',TRUE);
			$temp_mk['###BTN_EDIT###'] = $this->lib->linkButton('编辑',$this->lib->selfT3Url(array('uid'=>$row['uid'],'back'=>$this->backurl),$this->flex['detailPid']),'icon-edit','btn-mini',TRUE);
			$temp_mk['###BTN_DEL###'] = $this->lib->linkButton('删除',$this->lib->selfT3Url(array('cmd'=>'del','uid'=>$row['uid'],'back'=>$this->backurl),$GLOBALS['TSFE']->id),'icon-remove','btn-mini',FALSE,TRUE);
			$content_items .= $this->cObj->substituteMarkerArray($tpl_items,$temp_mk);
		}
		
		$this->db->sql_free_result($res);
		$content = $this->cObj->substituteSubpart($tpl,'###ITEMS###',$content_items);
		
		
		$mk = array(
			'###HEADER###' => $this->cObj->data['header'],
			'###ADD_NEW###' => $this->lib->linkButton('添加新部门',$this->lib->selfT3Url(array('cmd'=>'add','back'=>$this->backurl),$this->flex['detailPid']),' icon-plus','btn-mini',TRUE),
		);

		$content = $this->cObj->substituteMarkerArray($content,$mk);
		return $content;
		
	}
	
	
	/**
	 * 部门删除
	 */
	function doDeleteManager(){
		
		if($this->get['cmd'] && 'del' == $this->get['cmd'] && $this->get['uid']){
			
			if($this->db->exec_UPDATEquery('tx_mfwcvolunteer_departments','uid='.$this->get['uid'],array('deleted' => 1))){
				
				$this->db->exec_UPDATEquery('tx_mfwcvolunteer_jobs','department_id='.$this->get['uid'],array('deleted' => 1));
				$this->lib->doLayout(array('message' => '删除成功','url' => urldecode($this->backurl)));
			}else{
				$this->lib->doLayout(array('message' => '删除失败'));
			}
			
		}
	}
	
	
	/**
	 * 职位列表
	 */
	function managerDetailView(){
		
		$saveInfos = $this->doSaveDepartmentInfos();
		if($saveInfos) return $saveInfos;
		
		
		$tpl = $this->cObj->getSubpart($this->template, '###MDETAIL_VIEW###');
		$tpl_items = $this->cObj->getSubpart($tpl, '###ITEMS###'); 
		
		$mk = array(
		
			'###HEADER###' => $this->cObj->data['header'],
			'###MSG###' => $this->msg,
			'###prefixId###' => $this->prefixId,
			'###department_uid###' => '',
			'###department_title###' => $this->lib->getSingleMarker('title','tx_mfwcvolunteer_departments',''),
			'###department_admin###' => $this->lib->getSingleMarker('admin','tx_mfwcvolunteer_departments',''),
			'###department_receive_email###' => $this->lib->getSingleMarker('receive_email','tx_mfwcvolunteer_departments',''),
			'###BTN_BACK###' => $this->lib->closeButton(),
			'###ACTION###' => $this->lib->selfT3Url($this->get,$GLOBALS['TSFE']->id),
		);
		
		
		$content_items = '';
		if($this->get['uid'] && $row = $this->db->exec_SELECTgetSingleRow('*',
							'tx_mfwcvolunteer_departments','deleted=0 AND hidden=0 AND uid='.$this->get['uid'])){
		
			//部门信息
			$mk['###department_uid###'] = '<input type="hidden" name="'.$this->prefixId.'[uid]" value="'.$row['uid'].'">';
			$mk['###department_title###'] = $this->lib->getSingleMarker('title','tx_mfwcvolunteer_departments',$row['title']);
			$mk['###department_admin###'] = $this->lib->getSingleMarker('admin','tx_mfwcvolunteer_departments',$row['admin']);
			$mk['###department_receive_email###'] = $this->lib->getSingleMarker('receive_email','tx_mfwcvolunteer_departments',$row['receive_email']);
		
			//部门职位
			$res = $this->db->exec_SELECTquery('uid,title','tx_mfwcvolunteer_jobs','deleted=0 AND hidden=0 AND department_id='.$this->get['uid'],'','uid asc');
			while($row = $this->db->sql_fetch_assoc($res)){
			
				$content_items .= $this->cObj->substituteMarker($tpl_items,'###job_title###',
										'<input type="text" name="'.$this->prefixId.'[jobs]['.$row['uid'].'][title]" value="'.$row['title'].'">');
			}
			$this->db->sql_free_result($res);
		}
		
		$content_items .= $this->cObj->substituteMarker($tpl_items,'###job_title###',
								'<input type="text" name="'.$this->prefixId.'[new][0][title]" value="">');
	
	
		$content = $this->cObj->substituteMarkerArray($tpl,$mk);
		$content = $this->cObj->substituteSubpart($content,'###ITEMS###',$content_items);
		return $content;
	}
	
	
	/**
	 * 保存信息
	 */
	function doSaveDepartmentInfos(){
	
		//debug($this->post,'post');
		
		if($this->post){
		
			//update department
			$ins = array(
				'tstamp' => strtotime('now'),
				'title' => $this->post['title'],
				'admin' => $this->post['admin'],
				'receive_email' => $this->post['receive_email'] ? 1 : 0,
			);
	
			if($this->post['uid']){
				$this->db->exec_UPDATEquery('tx_mfwcvolunteer_departments','uid='.$this->post['uid'], $ins);
				$department_id = $this->post['uid'];
			}else{
				$ins['crdate'] = strtotime('now');
				$ins['pid'] = $this->flex['storagePid'];
				$this->db->exec_INSERTquery('tx_mfwcvolunteer_departments', $ins);
				$department_id = $this->db->sql_insert_id();
			}
			
			
			//update jobs
			if($this->post['jobs']){
				foreach($this->post['jobs'] as $uid => $title){
					$ups = array('deleted'=>1,'tstamp' => strtotime('now')); //标题为空，则标记当前职位删除
					if($title['title'] && trim($title['title']) != ''){
						$ups['deleted'] = 0;
						$ups['title'] = $title['title'];
					}
					$this->db->exec_UPDATEquery('tx_mfwcvolunteer_jobs','department_id='.$department_id.' AND uid='.$uid, $ups);
				}
			}
			
			//add jobs
			if($this->post['new']){
				foreach($this->post['new'] as $uid => $title){
					
					if($title['title'] && trim($title['title']) != ''){
						$ins = array(
							'tstamp' => strtotime('now'),
							'crdate' => strtotime('now'),
							'department_id' => $department_id,
							'title' => $title['title'],
						);
						$this->db->exec_INSERTquery('tx_mfwcvolunteer_jobs', $ins);
					}
				}
			}
		
			return $this->lib->notificationBox(urldecode($this->backurl),
				$this->lib->selfT3Url(array('cmd'=>'add','back'=>$this->backurl),$GLOBALS['TSFE']->id));
		}
	}
	
	
	/**
	 * 添加志愿者编号
	 */
	function volunteerAddId(){

		$res = $this->db->exec_SELECTquery('uid,tstamp','fe_users','FIND_IN_SET('.$this->flex['volunteerGroup'].',usergroup) AND tx_mfwcvolunteer_id is Null');
		while($row = $this->db->sql_fetch_assoc($res)){
			$this->db->exec_UPDATEquery('fe_users','uid='.$row['uid'],array('tx_mfwcvolunteer_id'=>date('Ymdhis',$row['tstamp']).rand(10,99)));
		}	
		$this->db->sql_free_result($res);
	}
	


	function init($conf){
	
        $this->conf = $conf;                   //store configuration
        $this->pi_loadLL();                    //Loading language-labels
        $this->pi_setPiVarDefaults();          //Set default piVars from TS
        $this->pi_initPIflexForm();            //Init FlexForm configuration for plugin
		$this->db = &$GLOBALS['TYPO3_DB'];
		$this->get = t3lib_div::_GET($this->prefixId);
		$this->post = t3lib_div::_POST($this->prefixId);
		$this->userData = &$GLOBALS['TSFE']->fe_user->user; //用户信息
		$this->msg;
		$this->errors = array();

		
		$this->lib = new tx_mfwcshoolinfos_lib($this);
		//include(t3lib_extMgm::extPath('fe_users').'ext_tables.php'); //加载其他公用字段
		include(t3lib_extMgm::extPath('mfwc_shoolinfos').'ext_tables.php'); //加载其他公用字段
		
		if($this->get['back']){
			$this->backurl = $this->get['back'];
		}else{
			$bPivars = $this->get;
			if(isset($bPivars['cmd']) && $bPivars['cmd'] == 'ajaxlist') unset($bPivars['cmd']);
			$this->backurl = urlencode($this->lib->selfT3Url($bPivars,$GLOBALS['TSFE']->id));
		}
		
		$this->lib->flexfromConfiguration();
		
     	// Get Template
        $templateFile = $this->conf['templateFile'] ? $this->conf['templateFile'] :  $this->flex['template'];
       	$templateFile ? $templateFile : $templateFile='EXT:'.$this->extKey.'/pi1/template.html';
       	$this->template = $this->cObj->fileResource($templateFile);
		
		$GLOBALS['TSFE']->additionalHeaderData[$this->extKey] .='
			<script src=" '.t3lib_extMgm::siteRelPath($this->extKey).'pi1/common.js" type="text/javascript"></script>
			<link rel="stylesheet"  type="text/css" href=" '.t3lib_extMgm::siteRelPath($this->extKey).'pi1/style.css"/>
		';
    }
}



if (defined('TYPO3_MODE') && isset($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['ext/mfwc_volunteer/pi1/class.tx_mfwcvolunteer_pi1.php'])) {
	include_once($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['ext/mfwc_volunteer/pi1/class.tx_mfwcvolunteer_pi1.php']);
}

?>